#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
添加last_activity字段到User表
"""

from app import create_app
from models import db, User
from datetime import datetime

def add_last_activity_field():
    """添加last_activity字段到User表"""
    app = create_app()
    
    with app.app_context():
        try:
            # 检查字段是否已存在
            inspector = db.inspect(db.engine)
            columns = [col['name'] for col in inspector.get_columns('users')]
            
            if 'last_activity' not in columns:
                print("正在添加last_activity字段...")
                
                # 添加字段
                db.engine.execute('ALTER TABLE users ADD COLUMN last_activity DATETIME DEFAULT CURRENT_TIMESTAMP')
                
                # 更新现有用户的last_activity为created_at
                db.engine.execute('UPDATE users SET last_activity = created_at WHERE last_activity IS NULL')
                
                print("last_activity字段添加成功！")
            else:
                print("last_activity字段已存在")
                
        except Exception as e:
            print(f"添加字段时出错: {e}")
            print("请手动执行以下SQL:")
            print("ALTER TABLE users ADD COLUMN last_activity DATETIME DEFAULT CURRENT_TIMESTAMP;")
            print("UPDATE users SET last_activity = created_at WHERE last_activity IS NULL;")

if __name__ == '__main__':
    add_last_activity_field()
